﻿using System;
using System.Threading;

namespace WholesaleOnline.Controller.Handlers
{
    public class AsyncResult : IAsyncResult
    {
        private AsyncCallback m_AsyncCallback = null;
        private ManualResetEvent m_Event = null;

        private object m_AsyncState = null;
        public object AsyncState { get { return m_AsyncState; } }

        public WaitHandle AsyncWaitHandle
        {
            get
            {
                if (m_IsCompleted)
                    return null;

                if (m_Event == null)
                    m_Event = new ManualResetEvent(false);
                return m_Event;
            }
        }

        public bool CompletedSynchronously { get { return false; } }

        private volatile bool m_IsCompleted = false;
        public bool IsCompleted { get { return m_IsCompleted; } }

        public AsyncResult(AsyncCallback callback, object extraData)
        {
            m_AsyncCallback = callback;
            m_AsyncState = extraData;
        }

        public void SetCompleted()
        {
            m_IsCompleted = true;
            ManualResetEvent waitEvent = Interlocked.CompareExchange(ref m_Event, null, null);
            if (null != waitEvent)
                waitEvent.Set();

            if (null != m_AsyncCallback)
                m_AsyncCallback(this);

        }
    }
}
